# -*- coding: utf-8 -*-
import re, urllib
from datetime import datetime
from dateutil.relativedelta import relativedelta as deltatime

def simplify_chars(word):
	#simplifiquem els diacrítics per a l'ordre alfabètic
	word = word.lower()
	pairs=[(u"àáâäãăǎąåā", "a"),(u'æǣ', "ae"),
		   (u'ḃɓ', "b"),
		   (u'çćčćĉċ', "c"),
		   (u'đḍďḋ', "d"), (u'ð', "dh"),
		   (u'èéêëẽēę', "e"),
		   (u'ḟƒ', "f"),
		   (u'ĝġģğ', "g"),
		   (u'ĥħ', "h"),
		   (u'ìíîïīį', "i"), (u'ĳ', "ij"),
		   (u'ĵ', "j"),
		   (u'ķ',"k"),
		   (u'ŀļḷḹľł',"l"),
		   (u'ñńň', "n"),
		   (u'òóôöõøōǫ', "o"), (u'œ', "oe"),
		   (u'ṗ', "p"),
		   (u'ŗřṛṝ', "r"),
		   (u'şṡšŝ', "s"), (u'ß', "ss"),
		   (u'ţṫṭ', "t"), (u'Þ', "th"),
		   (u'ùúûüŭūų', "u"),
		   (u'ẁŵẅƿ', "w"),
		   (u'ýỳŷÿȳỹ', "y"),
		   (u'źžż', "z")]

	for pair in pairs:
		for char in pair[0]:
			word = word.replace(char, pair[1])
	word=word.replace(u"l·l","ll")
	word = re.sub("\W","!", word)
	return word

def sort_list(old_list):
	#ordena una llista
	simplifiedlist={}
	for word in old_list:
		simplifiedlist[simplify_chars(word)]=word
	new_list=[]
	for word in sorted(simplifiedlist.keys()):
		new_list.append(simplifiedlist[word])
	return new_list

def showTimeDiff(date1, date2):
	from datetime import datetime
	from dateutil.relativedelta import relativedelta as deltatime

	timedivs={"y":"any","m":"mes","d":"dia","H":"hora","M":"minut","S":"segon"}
	plural={"dia":"dies","hora":"hores","mes":"mesos"}
	def get_plural(div):
		return plural[timedivs[div]] if plural.has_key(timedivs[div]) else timedivs[div]+"s"
	#dates=reversed(sorted([date1, date2]))
	dates=[date1, date2]
	dates.sort()
	dates.reverse()
	diff=deltatime(dates[0],dates[1])
	diffs_txt=""
	items=[	("y", diff.years), ("m", diff.months), ("d", diff.days),
			("H", diff.hours), ("M", diff.minutes),("S", diff.seconds)]
	diffs=[]
	for item in items:
		diff=""
		if item[1]>1:
			diff="%s" % get_plural(item[0])
		elif item[1]==1:
			diff="%s" % timedivs[item[0]]
		if item[1]>0:
			diff="%i %s"  % (item[1],diff)
			diffs.append(diff)
	if len(diffs)>1:
		print diffs
		diffs_txt=", ".join(diffs[:-1])
		diffs_txt+=" i "+diffs[-1]
	elif len(diffs)==1:
		diffs_txt=diffs[0]
	return diffs_txt

def capitalize(word):
	if not isinstance(word, basestring): return
	if len(word)>1:
		word=word[0].upper()+word[1:]
	elif len(word)==1:
		word=word.upper()
	return word

class Chrono:
	#2010-12-04
	def __init__(self):
		self.alpha = datetime.now()
		self.omega = None
		print self.alpha.strftime("%Y-%m-%d %H:%M")

	def start(self):
		return self.alpha

	def end(self):
		return self.omega

	def reset():
		self.alpha = datetime.now()
		self.omega = None
		return self.alpha

	def ellapsed(self):
		t = deltatime(datetime.now(), self.alpha)
		return (t.years, t.months, t.days, t.hours, t.minutes, t.seconds, t.microseconds)

	def stop(self):
		if not self.omega: self.omega = datetime.now()
		t = deltatime(self.omega, self.alpha)
		return self.omega, (t.years, t.months, t.days, t.hours, t.minutes, t.seconds, t.microseconds)

	def show(self):
		now = datetime.now()
		t = deltatime(now, self.alpha)
		print "%i %i:%i:%i" % (t.days, t.hours, t.minutes, t.seconds)
		return now, (t.years, t.months, t.days, t.hours, t.minutes, t.seconds, t.microseconds)

def convert_bytes(bytes):
	#2010/12/07 00:51
	#http://snipperize.todayclose.com/snippet/py/Converting-Bytes-to-Tb/Gb/Mb/Kb--14257/
	bytes = float(bytes)
	if bytes >= 1099511627776:
		terabytes = bytes / 1099511627776
		size = '%.2f TB' % terabytes
	elif bytes >= 1073741824:
		gigabytes = bytes / 1073741824
		size = '%.2f GB' % gigabytes
	elif bytes >= 1048576:
		megabytes = bytes / 1048576
		size = '%.2f MB' % megabytes
	elif bytes >= 1024:
		kilobytes = bytes / 1024
		size = '%.2f KB' % kilobytes
	else:
		size = '%i B' % bytes
	return size

def local_fmt(x):
	locale.locale_aliases
	locale.setlocale(locale.LC_ALL, "Catalan_Spain.1252")
	#currency
	locale.currency(x, grouping=True)
	#numbers
	locale.format("%f", x, grouping=True)

def format_number(n, places=2, decsep=",", thsep="."):
	if isinstance(n, int) and places>0:
		n = "%.2f" % float(n)
	n=str(n)
	n=n.split(".")
	if places and len(n)==2 and len(n[1])>0: n[1] = n[1][:places]
	f=[]
	i=0
	for s in n:
		i+=1
		r=[]
		j=0
		if i==1:
			for c in reversed(s):
				if j==3:
					r.insert(0,thsep)
					j=0
				j+=1
				r.insert(0,c)
		else:
			for c in s:
				if j==3:
					r.append(thsep)
					j=0
				j+=1
				r.append(c)
		f.append(''.join(r))
	if len(n)==2: f=decsep.join(f)
	else: f=f[0]
	return f

def has_wildcard(mask, match):
	#check if string has IRC wildcards
	mask = mask.replace('?', '[\\w|\\W]').replace('*', '[\\w|\\W]+')
	regex = re.compile(mask, re.IGNORECASE)
	if regex.match(match) == None: return False
	else: return True

def wildcard_to_regexp(string):
	#Wildcards used in IRC are "?" and "*".
	#Transalte they to a correct regular expression.
	string = string.replace("?",".").replace("*",".*")
	return string

def escape_for_regexp(string):
	#Standardize character as escape caracter in a regular expression
	for char in '^$[].|?+-*{}()':
		string = string.replace(char, r'\%s' % char)
	return string

def decode(txt=""):
	ntxt=""
	try:
		ntxt=unicode(txt, 'utf-8')
	except UnicodeError:
		try:
			ntxt=unicode(txt, 'latin-1')
		except UnicodeError:
			try:
				ntxt = txt.decode('cp1252')
			except Exception:
				print "unknown coding."
	return ntxt

def encode(text, encoding="utf-8"):
	if isinstance(text, unicode):
		try: text = text.encode(encoding)
		except UnicodeEncodeError, e:
			pass
	return text

def apiparams(obj):
	if isinstance(obj, (list,tuple)):
		return "|".join([quote(s) for s in obj])
	elif isinstance(obj, (int, float)):
		return str(obj)
	return quote(obj)

def urlencode(params):
	if not params:
		return None
	if hasattr(params, 'iteritems'):
		iterator = params.iteritems()
	else:
		iterator = iter(params)
	l = []
	for key, value in iterator:
		key = apiparams(key)
		value = apiparams(value)
		l.append("%s=%s" % (key, value))
	return '&'.join(l)

def quote(string, encoding = "utf-8"):
	return urllib.quote(encode(string, encoding))

def wikiquote(string):
	string = urllib.quote(encode(string))
	string = string.replace('%2F', '/')
	string = string.replace("%3A", ":")
	string = string.replace("%20", "_")
	return string

def gooquote(string):
	string = urllib.quote(encode(string))
	print string
	string = string.replace('%2F', '/')
	string = string.replace("%3A", ":")
	string = string.replace("%20", "+")
	return string

def find_user(user, users):
	for nick in users:
		user = re.search(r"(%s[^ ]+)" % user, nick, re.I)
		if user:
			user=user.group(1)
			return user
	return ""

def _trans(file, string):
	try:
		exec("from lang import %s" % file)
		variables=vars(eval(file))
		for var in variables.keys():
			if var.startswith("__"): continue
			if variables[var].has_key(string):
					return variables[var][string]
	except:
		print "functions.py exception passed"
	return string

def is_ip(string):
	#poor regexp: "\d{1,3}(?:\.\d{1,3}){3}"
	return bool(
		re.match(
			'^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)'
			'(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$',
			string
		)
	)

def get_ip(string):
	m = re.search(
		'(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)'
		'(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d))'
		'(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d))'
		'(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d))',
		string
	)
	if m:
		return tuple([int(x) for x in m.groups()])

def join_list(lst, lng="en"):
	if isinstance(lst, (list, tuple)):
		if len(lst)>1:
			rtn="%s %s %s" % (", ".join(lst[:-1]), _trans(lng, "and"), lst[-1])
		elif len(lst)==1:
			rtn = lst[0]
		else:
			rtn = "&r;(empty)&N;"
		return rtn

def join_userlist(lst, usrlist=None, lng="en"):
	if isinstance(lst, (list, tuple)):
		if len(lst)>1:
			i=0
			for u in sort_list(lst):
				c= "+e" if i % 2 == 0 else "l"
				u = u"&%s;%s·%s&N;" % (c, u[0], u[1:]) if not usrlist else  \
					u"&%s;%s·%s&N;" % (c, u[0], u[1:]) if u in usrlist else \
					u"&%s;%s&N;" % (c, u)
				lst[i]=u
				i+=1
			rtn = u"%s %s %s" % (", ".join(lst[:-1]), _trans(lng, "and"), lst[-1])
		elif len(lst)==1:
			rtn = u"&l;%s·%s&N;" % (lst[0][0], lst[0][1:]) if not usrlist else  \
				u"&l;%s·%s&N;" % (lst[0][0], lst[0][1:]) if lst[0] in usrlist else \
				u"&l;%s&N;" % (lst[0])
		else:
			rtn = _trans(lng, "&r;(empty)&N;")
		return rtn

def status(boolean):
	return {
		False: "&B;&r;off&N;",
		True: "&B;&e;on&N;"
	}[boolean]
